package com.services.weather;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParserException;

import com.services.weather.YahooForecastParser.Item;
import com.services.weather.YahooXmlParser.Place;

import android.os.AsyncTask;


public class RetrieveWeather {
	String location;
	String forecastDesc;
	String forecastCode;
	List<Place> locations;
	YahooXmlParser xmlParser;
	
	@SuppressWarnings("unchecked")
	public RetrieveWeather(String location) {
		this.location = location;
		locations = null;
		xmlParser = new YahooXmlParser();
	    try {
			locations = xmlParser.parse(downloadUrl(location));
			getForecast();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getForecastCode() {
		return forecastCode;
	}

	public String getDescription() {
		return forecastDesc;
	}
	
	@SuppressWarnings("unchecked")
	private void getForecast() {
		Item result = null;
		String woeid = null;
		Place place = null;
		
		// take the first location
		place = locations.get(0);
		woeid = place.woeid;
		
		
		String forecastUrl = "http://weather.yahooapis.com/forecastrss?w=" + woeid;
		List<Item> forecasts = null;
		YahooForecastParser parser = new YahooForecastParser();
		
	    try {
			forecasts = parser.parse(downloadUrl(forecastUrl));
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    // only take the first forecast
		result = forecasts.get(0);
		
		forecastCode = result.code;
		forecastDesc = result.description;

		
	}
	
	private InputStream downloadUrl(String urlString) throws IOException {
	    URL url = new URL(urlString);
	    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	    conn.setReadTimeout(10000 /* milliseconds */);
	    conn.setConnectTimeout(15000 /* milliseconds */);
	    conn.setRequestMethod("GET");
	    conn.setDoInput(true);
	    // Starts the query
	    conn.connect();
	    return conn.getInputStream();
	}

}


